package com.jwaoo.chat.session.avchat;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.GestureDetectorCompat;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.dx.as.ToastUtil;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.log.LogUtil;
import com.jwaoo.chat.ChatHelpter;
import com.jwaoo.chat.R;
import com.jwaoo.chat.activity.module.fromapp.AppInstance;
import org.webrtc.SurfaceViewRenderer;

/**
 * Created by jwaoo on 2017/11/8.
 */

public class AChatView {
    private WindowManager windowManager;
    private MyFloatView bigView;
    public MyLayoutParam layoutParams;
    private View videoView_top;
    private View voiceView_top;
    private View canelView_bottom;
    private View waitingResponseView_bottom;
    private View chatingView_bottom;
    private View view_top;
    private View view_loading;
    private View view_bottom;
    private View btn_scale;
    private View view_div;
    private View view_option;
    private View btn_close_camera;
    private TextView tv_time;
    private View tv_div_state;
    private View view_scale;
    private int avChatType;
    private SurfaceViewRenderer fullscreenRenderer;
    private SurfaceViewRenderer smallView;
    private View btn_open_video;
    private boolean isComming;
    private boolean isSmall;
    private View base_view;
    private TextView log;
    private TextView tv_local_div_state;
    private int height = 0;
    private int width = 0;
    private CallbackListener listener;
    private View watting_option_view;
    private ProgressBar progress;
    private boolean cameraState[] = new boolean[]{false,false};
    private final int s_height = ChatHelpter.getContext().getResources().getDimensionPixelSize(R.dimen.av_small_view_h)
            ,s_width = ChatHelpter.getContext().getResources().getDimensionPixelSize(R.dimen.av_small_view_w);
    private View btn_request_div;
    public AChatView(WindowManager windowManager,CallbackListener listener,int avChatType ,boolean iscoming) {
        this.windowManager = windowManager;
        this.avChatType = avChatType;
        this.isComming = iscoming;
        this.listener = listener;
        initBaseView();
    }

    public View getBaseView (){
        return bigView;
    }

    public void initBaseView(){
        bigView = (MyFloatView)View.inflate(ChatHelpter.getContext(), R.layout.activity_avchat,null);
        bigView.setOnKeyDownListener(new MyFloatView.OnKeyDownListener() {
            @Override
            public void onBackKeyClick() {

            }
        });

        bigView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                v.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (avChatType == AVChatType.VIDEO.getValue() && !isComming) {
                            view_loading.setVisibility(View.GONE);
                        }
                    }
                },500);
            }

            @Override
            public void onViewDetachedFromWindow(View v) {

            }
        });


        final GestureDetectorCompat mDetector = new GestureDetectorCompat(ChatHelpter.getContext(),onGestureListener);
        bigView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LogUtil.d("========","bigView setOnTouchListener");
                if (isSmall){
                    mDetector.onTouchEvent(event);
                    return false;
                }
                return true;
            }
        });
        initView();

        if (CommonUtils.isEnFloat()) {
            layoutParams = new MyLayoutParam(new MyLayoutParam.Listener() {
                @Override
                public void updateView() {
                    windowManager.updateViewLayout(bigView,layoutParams);
                }
            });
            bigView.setFocusableInTouchMode(true);
            layoutParams.format = PixelFormat.TRANSLUCENT;
            layoutParams = (MyLayoutParam) ChatHelpter.getFloatConfig(layoutParams);
            layoutParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// 焦点
            layoutParams.gravity = Gravity.TOP|Gravity.LEFT;
            windowManager.addView(bigView,layoutParams);
        }else {
            bigView.setVisibility(View.VISIBLE);
        }

    }

    private void initView(){
        videoView_top = bigView.findViewById(R.id.view_video);
        voiceView_top = bigView.findViewById(R.id.view_voice);
        view_top = bigView.findViewById(R.id.view_top);
        view_bottom = bigView.findViewById(R.id.view_bottom);
        view_div = bigView.findViewById(R.id.view_div);
        tv_div_state = bigView.findViewById(R.id.tv_div_state);
        view_option = bigView.findViewById(R.id.view_option);
        btn_open_video = bigView.findViewById(R.id.btn_open_video);
        log = bigView.findViewById(R.id.log);
        view_loading = bigView.findViewById(R.id.view_loading);
        final boolean isVoice = avChatType == AVChatType.AUDIO.getValue();
        cameraState[0] = isVoice;
        voiceView_top.setVisibility(isVoice ? View.VISIBLE : View.GONE);
        videoView_top.setVisibility(isVoice ? View.GONE : View.VISIBLE);
        btn_scale = bigView.findViewById(R.id.btn_scale);

        tv_time =  bigView.findViewById(R.id.tv_time);
        view_scale = bigView.findViewById(R.id.view_scale);
        btn_close_camera = bigView.findViewById(R.id.btn_close_camera);
        tv_local_div_state = bigView.findViewById(R.id.tv_local_div_state);
        smallView =  bigView.findViewById(R.id.pip_video_view);
        smallView.setZOrderOnTop(true);
        smallView.setZOrderMediaOverlay(true);
        fullscreenRenderer =  bigView.findViewById(R.id.fullscreen_video_view);
        watting_option_view = bigView.findViewById(R.id.watting_option_view);
        final GestureDetectorCompat mDetector = new GestureDetectorCompat(ChatHelpter.getContext(),onGestureListener);
        smallView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mDetector.onTouchEvent(event);
                return false;
            }
        });

        bigView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isSmall){
                    mDetector.onTouchEvent(event);
                }
                return false;
            }
        });

        fullscreenRenderer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (view_option.getVisibility() == View.VISIBLE)
                    hideBottomView(false);
                if (isSmall) {
                    if (!cameraState[0] && !cameraState[1]) {
                        smallView.setVisibility(View.VISIBLE);
                    }
                    scaleView();
                }
            }
        });
        base_view = bigView.findViewById(R.id.base_view);

        initBottomView();
        initBluetoothOption();


//        bigView.findViewById(R.id.log_open).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                isRecord = !isRecord;
//                bigView.getHandler().post(new Runnable() {
//                    @Override
//                    public void run() {
//                        log.setText("");
//                    }
//                });
//            }
//        });


    }


    private boolean isRecord = true;


    public void onLog(final String str){
        bigView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (isRecord){
                    log.append(str);
                }
            }
        });
    }

    int [][] drawable = {{R.drawable.vediochat_senseband_control_icon_01},{},{},{},{},{},{},{},{}};
    private void initBluetoothOption(){

        bigView.findViewById(R.id.btn_1).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_2).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_3).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_4).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_5).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_6).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_7).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_8).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_plus).setOnClickListener(clickListener);
        bigView.findViewById(R.id.btn_reduce).setOnClickListener(clickListener);
        progress = bigView.findViewById(R.id.progress);
        progress.setProgress(1);
//        bigView.findViewById(R.id.mei).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                listener.onMeiYan();
//            }
//        });
    }

    private int mode = 5;
    private int lv = 1;

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (v.getId() == R.id.btn_plus ){
                lv++;
                if (lv > 18) lv = 18;
            }else if (v.getId() == R.id.btn_reduce){
                lv--;
                if (lv < 1) lv = 1;
            }else {
                int current = Integer.parseInt(v.getTag().toString().trim());
                if (current == mode) {
                    mode = 0;
                    lv = 0;
                }else {
                    mode = current;
                    lv = 5;
                }
            }
            listener.onBluetoothOption(mode,lv);
//            progress.setProgress(lv);
        }
    };

    private void hideAllView(boolean hide){
        view_top.setVisibility( hide ? View.GONE : View.VISIBLE);
        view_bottom.setVisibility( hide ? View.GONE : View.VISIBLE);
        if (!hide && cameraState[0]) {
            btn_close_camera.setVisibility(View.VISIBLE);
        }else{
            btn_close_camera.setVisibility(View.GONE);
        }

    }

    public void hideBottomView(boolean hide){
        chatingView_bottom.setVisibility(hide ? View.GONE : View.VISIBLE);
        view_option.setVisibility(hide ? View.VISIBLE : View.GONE);
    }

    private boolean hadAccept;
    public void doAccept(){
        hadAccept = true;
        btn_request_div.setBackgroundResource(R.drawable.vediochat_senseband_successful_btn);
    }

    private void initBottomView(){

        canelView_bottom = bigView.findViewById(R.id.btn_cancel);
        waitingResponseView_bottom = bigView.findViewById(R.id.view_waiting_response);
        chatingView_bottom = bigView.findViewById(R.id.view_chating);

        if (isComming) {
            base_view.setVisibility(View.GONE);
            waitingResponseView_bottom.setVisibility(View.VISIBLE);
        } else {
            canelView_bottom.setVisibility(View.VISIBLE);
            base_view.setVisibility(View.VISIBLE);
        }

        bigView.findViewById(R.id.btn_refuse).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onHang();
            }
        });

        bigView.findViewById(R.id.btn_receive).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onStartAvChat();
                watting_option_view.setVisibility(View.GONE);
                bigView.findViewById(R.id.lb_waiting).setVisibility(View.VISIBLE);
            }
        });

        bigView.findViewById(R.id.btn_refuse).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onButtonClick(AVChatState.refused);
            }
        });

        bigView.findViewById(R.id.btn_hangup).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onButtonClick(AVChatState.hangup);
            }
        });

        btn_scale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onScaleBtnClicked();
            }
        });


        bigView.findViewById(R.id.btn_switch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onSwitchCamera();
            }
        });

        bigView.findViewById(R.id.btn_close_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onCloseCamera(true);
                hideSmallView(false,true);
                btn_close_camera.setVisibility(View.GONE);
                btn_open_video.setVisibility(View.VISIBLE);
                onVideoChatConnectedChanged();
            }
        });

        btn_request_div = bigView.findViewById(R.id.btn_request_div);
        btn_request_div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hadAccept){
                    hideBottomView(true);
                }else {
                    listener.onRequestDiv();
                }
            }
        });

        bigView.findViewById(R.id.btn_bluetooth).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onConnectBluetooth();
            }
        });

        canelView_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.onButtonClick(AVChatState.cancel);
            }
        });

        btn_open_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_open_video.setVisibility(View.GONE);
                listener.onCloseCamera(false);
                hideSmallView(false,false);
                onVideoChatConnectedChanged();
                btn_close_camera.setVisibility(View.VISIBLE);
            }
        });
    }

    public void onScaleBtnClicked() {
        hideAllView(true);
        smallView.setVisibility(View.GONE);
        scaleView();
    }

    public void hideSmallView(final boolean beHide,final boolean hide){
        if (!hide && (cameraState[0] && cameraState[1])) {
            cameraState[beHide ? 1 : 0] = hide;
            return;
        }
        cameraState[beHide ? 1 : 0] = hide;
        bigView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                smallView.setVisibility(hide ? View.GONE : View.VISIBLE);
            }
        });
    }

    public SurfaceViewRenderer getFullscreenRenderer() {
        return fullscreenRenderer;
    }

    public void updateTime(final String str){
        bigView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                tv_time.setText(str);
            }
        });

    }

    public SurfaceViewRenderer getSmallView() {
        return smallView;
    }

    public void onConnected(){
        if (CommonUtils.isEnFloat() && height == 0){
            height = layoutParams.height;
            width = layoutParams.width;
        }

        videoView_top.setVisibility(View.GONE);
        canelView_bottom.setVisibility(View.GONE);
        waitingResponseView_bottom.setVisibility(View.GONE);
        chatingView_bottom.setVisibility(View.VISIBLE);
        btn_scale.setVisibility(CommonUtils.isEnFloat() ? View.VISIBLE : View.GONE);
        if (avChatType == AVChatType.VIDEO.getValue()){
            cameraState[1] = false;
            base_view.setVisibility(View.VISIBLE);
            bigView.getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                view_loading.setVisibility(View.GONE);
                }
            },200);
        }
        view_scale.setVisibility(View.VISIBLE);
    }

    private void moveView(MotionEvent event){
        if (!isSmall) {
            Log.d("==========","small");
            smallView.layout((int) event.getRawX(), (int) event.getRawY(), (int) event.getRawX() + smallView.getWidth(), (int) event.getRawY() + smallView.getHeight());
        } else {
            Log.d("==========","not small");
            layoutParams.gravity = Gravity.TOP|Gravity.LEFT;
            layoutParams.x = (int)(event.getRawX());
            layoutParams.y = (int)(event.getRawY());
            windowManager.updateViewLayout(bigView,layoutParams);
        }
    }

    public void hideFloatView(final boolean hide){
        bigView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                bigView.setVisibility(hide ? View.GONE : View.VISIBLE);
            }
        });
    }

    public void onDivConnected(final boolean isConnected){
        bigView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                view_div.setVisibility(isConnected ? View.VISIBLE : View.GONE);
                tv_local_div_state.setVisibility(isConnected ? View.VISIBLE : View.GONE);
            }
        });

    }

    public Context getContext(){
        return bigView.getContext();
    }

    public Handler getHandler(){
        return bigView.getHandler();
    }

    public void scaleView(){
        layoutParams.gravity = Gravity.TOP|Gravity.RIGHT;
        ObjectAnimator animator1 = ObjectAnimator.ofInt(layoutParams, "height", isSmall ? s_height : height, !isSmall ? s_height : height);
        ObjectAnimator animator2 = ObjectAnimator.ofInt(layoutParams, "width", isSmall ? s_width : width, !isSmall ? s_width : width);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(animator1).with(animator2);
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.setDuration(200);
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {

                if (!isSmall){
                    bigView.getHandler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            hideAllView(false);
                        }
                    },200);
                }
                if (!isSmall && cameraState[0] && cameraState[1] ){
                    LogUtil.e("=======","animation end");
                    smallView.setVisibility(View.VISIBLE);
                    smallView.setAlpha(0.0f);
                    ObjectAnimator animator = ObjectAnimator.ofFloat(smallView, "alpha", 0.0f,1.0f);
                    animation.setDuration(1000);
                    animator.start();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        isSmall = !isSmall;
        if (!isSmall){
            Class<?> cls = AppInstance.getInstance().getCurrentActivity();
            Intent intent = null;
            if (cls != null){
                intent = new Intent(ChatHelpter.getContext(), cls);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ChatHelpter.getContext().startActivity(intent);
            }
        }

        animatorSet.start();
    }

    private  GestureDetector.OnGestureListener onGestureListener = new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {

            if (isSmall){
                scaleView();
            }else {
                listener.onSwapRender();
            }
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            moveView(e2);
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }

    };

    public void removeView(){
        windowManager.removeView(bigView);
    }

    public void showTagInfo(){
        bigView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                if (!isComming)
                    ToastUtil.makeText(ChatHelpter.getContext(),"无人接听，稍后再试...").show();
                else
                    ToastUtil.makeText(ChatHelpter.getContext(),"等待超时...").show();
            }
        });
    }

    public void onOtherDivConnected(final boolean isConnected){
        bigView.getHandler().post(new Runnable() {
            @Override
            public void run() {
                tv_div_state.setVisibility(isConnected ? View.VISIBLE : View.GONE);
            }
        });
    }

    public void onRemoteCameraClosed(boolean isClosed){
        cameraState[1] = isClosed;
        onVideoChatConnectedChanged();
    }

    private void onVideoChatConnectedChanged(){
        final boolean isAllClose = cameraState[0] && cameraState[1];
        bigView.post(new Runnable() {
            @Override
            public void run() {
                view_loading.setVisibility(isAllClose ? View.VISIBLE : View.GONE);
//        videoView_top.setVisibility(isAllClose ? View.GONE :View.VISIBLE);
                voiceView_top.setVisibility(isAllClose ? View.VISIBLE : View.GONE);
//                btn_open_video.setVisibility(isAllClose ? View.VISIBLE : View.GONE);
            }
        });

    }

    public interface CallbackListener{
        void onButtonClick(AVChatState avChatState);
        void onSwapRender();
        void onSwitchCamera();
        void onStartAvChat();
        void onHang();
        void onConnectBluetooth();
        void onRequestDiv();
        void onBluetoothOption(int mode,int level);
        void onCloseCamera(boolean close);
        void onMeiYan();
    }
}
